<?php
/**
 * +--------------------------------------------------------+
 * @Created by PhpStorm.
 * @Category AdminService.php
 * @Depiction:
 * Author: hwy
 * Date: 2021/2/20  16:52
 * +--------------------------------------------------------+
 */

namespace App\Services;


use App\Exceptions\ResponseException;
use App\Models\Admin;
use App\Models\ModelHasRole;
use App\Models\Role;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class AdminService extends BaseService
{
    protected $admin;
    protected $roleService;


    public function __construct()
    {
        $this->admin = new Admin();

        $this->roleService = RoleService::getInstance();
    }

    /**
     * @param $id
     * @return Builder|Model|object|null
     * @Depiction
     * @Author hwy
     * @Date 2021/3/17  13:43
     */
    public function getOne($id)
    {
        $admin = $this->admin->query()
            ->select('admins.id', 'admins.name', 'admins.email', 'admins.created_at', 'admins.updated_at', 'roles.display_name as roles_name', 'roles.id as roles_id')
            ->join('model_has_roles', 'model_has_roles.model_id', '=', 'admins.id')
            ->join('roles', 'model_has_roles.role_id', '=', 'roles.id')
            ->where('admins.id', $id)
            ->first();

        return $admin;
    }

    /**
     * @param $params
     * @return array
     * @Depiction 获取列表
     * @Author hwy
     * @Date 2021/3/15  16:53
     */
    public function getList($params): array
    {
        $query = $this->admin->query();

        $query = $query->select('admins.id', 'admins.name', 'admins.email', 'admins.created_at', 'admins.updated_at', 'roles.display_name as roles_name')
            ->join('model_has_roles', 'model_has_roles.model_id', '=', 'admins.id')
            ->join('roles', 'model_has_roles.role_id', '=', 'roles.id');

        $perPage = $this->perPage($params);

        if (!empty($params['name'])) {
            $query = $query->where('admins.name', 'like', '%' . $params['name'] . '%');
        }
        if (!empty($params['role'])) {
            $query = $query->where('roles.id', $params['role']);
        }
        if (!empty($params['created_at'])) {
            $times = explode(' - ', $params['created_at']);
            $query = $query->whereBetween('created_at', $times);
        }

        $list = $query->paginate($perPage)->toArray();

        return return_success_msg(ResponseException::REQUEST_SUCCESS_MESSAGE, $list);
    }

    /**
     * @param $params
     * @return array
     * @Depiction
     * @Author hwy
     * @Date 2021/3/17  11:18
     */
    public function addData($params)
    {
        DB::beginTransaction();
        $admin_data = [
            'name' => $params->name,
        ];
        //如果传password 则加密
        if (!empty($params->password)) {
            $admin_data['password'] = bcrypt($params->password);
        } else {
            $admin_data['password'] = bcrypt('a123456');
        }

        try {
            $result = $this->admin->query()->create($admin_data);

            if (!empty($params->role_id) && $result) {
                $role = $this->roleService->getOne($params->role_id)->name;
                $res  = $result->assignRole($role);
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return return_error_msg(exception_msg($e->getMessage()));
        }

        if (empty($result) || (!empty($params->role_id) && empty($res))) {
            DB::rollBack();
            return return_error_msg(ResponseException::ERROR_ADD_MESSAGE);
        } else {
            DB::commit();
            return return_success_msg(ResponseException::SUCCESS_ADD_MESSAGE);
        }
    }

    /**
     * @param $params
     * @return array
     * @Depiction
     * @Author hwy
     * @Date 2021/3/17  13:44
     */
    public function editData($params)
    {
        DB::beginTransaction();
        $admin = $this->admin->query()->find($params->id);
        if(false == $admin){
            return return_error_msg(ResponseException::DATA_NOT_EXIST_MESSAGE);
        }

        //如果传password 则加密
        if (!empty($params->password)) {
            $password = bcrypt($params->password);
        } else {
            $password = $admin->password;
        }

        $admin->name     = $params->name;
        $admin->password = $password;
        try {
            $result = $admin->save();
            if (!empty($params->role_id)) {
                $model_has_roles = ModelHasRole::query()->where('model_id', $admin->id)->delete();
                $role = $this->roleService->getOne($params->role_id)->name;
                $res  = $admin->assignRole($role);
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return return_error_msg(exception_msg($e->getMessage()));
        }

        if (empty($result)) {
            DB::rollBack();
            return return_error_msg(ResponseException::ERROR_EDIT_MESSAGE);
        } else {
            DB::commit();
            return return_success_msg(ResponseException::SUCCESS_EDIT_MESSAGE);
        }

    }

    /**
     * @param $ids
     * @return array
     * @Depiction
     * @Author hwy
     * @Date 2021/3/17  13:42
     */
    public function delData($ids)
    {
        if (is_string($ids)) {
            $ids = [$ids];
        }
        $data = $this->admin->query()->whereIn('id', $ids)->get();
        if (empty($data)) {
            return return_error_msg(ResponseException::DATA_NOT_EXIST_MESSAGE);
        }

        DB::beginTransaction();
        try {
            foreach ($data as $value) {
                $model_has_roles = ModelHasRole::where('model_id', $value->id)->delete();
                $del          = $value->delete();
            }
        } catch (\Exception $e) {
            return return_error_msg(exception_msg($e->getMessage()));
        }

        if ($del) {
            DB::commit();
            return return_success_msg(ResponseException::SUCCESS_DELETE_MESSAGE);
        } else {
            return return_error_msg(ResponseException::ERROR_DELETE_MESSAGE);
        }
    }

}
